package chat.clients.fb.helper;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import java.util.Iterator;
import java.util.List;

public class FBMessageListener implements MessageListener, Runnable {

    private final XMPPConnection connection;
    private List<RosterEntry> friends;

    public FBMessageListener(XMPPConnection connection) {
        this.connection = connection;
        new Thread(this).start();
    }

    public void setFriends(List<RosterEntry> friends) {
        this.friends = friends;
    }

    public void processMessage(Chat chat, Message message) {
        System.out.println();
        final Iterator<RosterEntry> iterator = friends.iterator();
        RosterEntry entry;

        while (iterator.hasNext()) {
            entry = iterator.next();

            if (entry.getUser().equalsIgnoreCase(chat.getParticipant()))
                break;
        }
    }

    public void run() {
        connection.getChatManager().addChatListener(
                (chat, createdLocally) -> {
                    if (!createdLocally) {
                        chat.addMessageListener(FBMessageListener.this);
                    }
                }
        );
    }
}